<template>
  <div>
    <I-Input
      v-model="fieldValue"
      is-link
      readonly
      :required="required"
      :rules="rules"
      :label="label"
      :input-align="inputAlign"
      :placeholder="placeholder"
      @click="showPickerClick"
    ></I-Input>
    <van-calendar
      :default-date="currentValue"
      v-model:show="showPicker"
      @cancel="showPicker = false"
      @confirm="onConfirm"
      v-bind="computedAttrs"
    />
  </div>
</template>

<script setup name="I-Calendar">
import { ref, computed } from 'vue'
import dayjs from 'dayjs'

const currentValue = ref()
const modelValue = defineModel({})
const props = defineProps({
  label: {
    type: String,
    default: ''
  },
  format: {
    type: String,
    default: 'YYYY-MM-DD'
  },
  title: {
    type: String,
    default: '选择日期'
  },
  required: {
    type: Boolean,
    default: false
  },
  rules: {
    type: Array,
    default: () => []
  },
  inputAlign: {
    type: String,
    default: 'right'
  },
  placeholder: {
    type: String,
    default: '请选择日期'
  },
  minDate: {
    type: Date,
    default: () => new Date(2000, 0, 1)
  },
  maxDate: {
    type: Date,
    default: () => new Date(2100, 11, 31)
  }
})
const $attrs = useAttrs()

const formatLabel = (val) => {
  if (!val) {
    return ''
  }
  if ($attrs.type == 'range') {
    if (val[0] && val[1]) {
      return `${dayjs(val[0]).format(props.format)} - ${dayjs(val[1]).format(props.format)}`
    }
    return ''
  }

  return dayjs(val).format(props.format)
}
const fieldValue = ref()

const showPicker = ref(false)

const showPickerClick = () => {
  showPicker.value = true
}
const onConfirm = (val) => {
  modelValue.value = val
  showPicker.value = false
}
// 计算属性，合并 props 和 $attrs
const computedAttrs = computed(() => {
  return {
    ...$attrs,
    minDate: props.minDate,
    maxDate: props.maxDate,
    title: props.title
  }
})

watch(
  () => modelValue.value,
  (value) => {
    fieldValue.value = formatLabel(value)
    currentValue.value = value
  },
  { immediate: true }
)
</script>

<style scoped>
</style> 